<template>
  <view class="coupon-detail">    
    <!-- 优惠券卡片 -->
    <view class="coupon-card" :class="{
      'used': source === 'user' && coupon.status === 1, 
      'expired': source === 'user' && coupon.status === 2
    }">
      <view class="coupon-top" :class="{
        'discount-coupon': coupon.tag === '折扣券' && !(source === 'user' && (coupon.status === 1 || coupon.status === 2)), 
        'free-coupon': coupon.goodsType === 2 && !(source === 'user' && (coupon.status === 1 || coupon.status === 2)),
        'gray-coupon': source === 'user' && (coupon.status === 1 || coupon.status === 2)
      }">
        <view class="coupon-tag" v-if="coupon.goodsType !== undefined">
          {{ coupon.goodsType === 0 ? '全场通用' : (coupon.goodsType === 2 ? '指定商品' : '') }}
        </view>
        <view class="coupon-amount">
          <text class="amount">{{ formatAmount(coupon.discount) }}</text>
          <text class="unit">元</text>
        </view>
        <view class="coupon-name">{{ coupon.name }}</view>
        <view class="coupon-desc">{{ coupon.desc }}</view>
      </view>
      <view class="coupon-bottom">
        <view class="coupon-time">
          <text class="label">有效期：</text>
          <text class="value" v-if="!coupon.days">{{ formatFullDate(coupon.startTime) }} - {{ formatFullDate(coupon.endTime) }}</text>
          <text class="value" v-else>领取后{{ coupon.days }}天内有效</text>
        </view>
        <view class="coupon-condition">
          <text class="label">使用条件：</text>
          <text class="value" v-if="coupon.min > 0">满{{ formatAmount(coupon.min) }}元可用</text>
          <text class="value" v-else>无门槛使用</text>
        </view>
        <view class="coupon-scope">
          <text class="label">适用范围：</text>
          <text class="value" v-if="coupon.goodsType === 0">全场通用</text>
          <text class="value" v-else-if="coupon.goodsType === 1">指定分类商品可用</text>
          <text class="value" v-else>指定商品可用</text>
        </view>
      </view>
    </view>
    
    <!-- 使用规则 -->
    <view class="rules-section">
      <view class="section-title">使用规则</view>
      <view class="rules-content">
        <view class="rule-item">本优惠券仅限在有效期内使用</view>
        <view class="rule-item">优惠券不可兑换现金，不可找零</view>
        <view class="rule-item">优惠券仅限在有效期内使用，过期自动作废</view>
        <view class="rule-item">如有疑问，请联系客服</view>
      </view>
    </view>
    
    <!-- 底部按钮 - 从我的优惠券进入且未使用 -->
    <view class="bottom-actions" v-if="source === 'user' && coupon.status === 0">
      <button 
        class="action-btn use-btn" 
        @tap="useCoupon"
      >
        去使用
      </button>
    </view>
    
    <!-- 底部按钮 - 从我的优惠券进入且已使用 -->
    <view class="bottom-actions" v-if="source === 'user' && coupon.status === 1">
      <button 
        class="action-btn disabled" 
        disabled
      >
        已使用
      </button>
    </view>
    
    <!-- 底部按钮 - 从我的优惠券进入且已过期 -->
    <view class="bottom-actions" v-if="source === 'user' && coupon.status === 2">
      <button 
        class="action-btn disabled" 
        disabled
      >
        已过期
      </button>
    </view>
    
    <!-- 底部按钮 - 从优惠券中心进入 -->
    <view class="bottom-actions" v-if="source === 'center'">
      <button 
        class="action-btn receive-btn" 
        :class="{'disabled': coupon.received}"
        :disabled="coupon.received"
        @tap="receiveCoupon"
      >
        {{ coupon.received ? '已领取' : '立即领取' }}
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      source: '', // 来源：user-我的优惠券，center-优惠券中心
      coupon: {
        id: 0,
        name: '',
        desc: '',
        discount: 0,
        min: 0,
        startTime: '',
        endTime: '',
        goodsType: 0,
        status: 0,
        tag: '',
        days: 0,
        received: false
      }
    }
  },
  computed: {
    isExpired() {
      if (this.coupon.status === 2) return true
      
      const now = new Date().getTime()
      const endTime = new Date(this.coupon.endTime.replace(/-/g, '/')).getTime()
      return endTime < now
    }
  },
  onLoad(options) {
    // 从URL参数中获取优惠券信息
    if (options) {
      // 设置来源
      this.source = options.source || 'user'
      
      this.coupon = {
        id: parseInt(options.id || 0),
        name: decodeURIComponent(options.name || ''),
        desc: decodeURIComponent(options.desc || ''),
        discount: parseFloat(options.discount || 0),
        min: parseFloat(options.min || 0),
        startTime: decodeURIComponent(options.startTime || ''),
        endTime: decodeURIComponent(options.endTime || ''),
        goodsType: parseInt(options.goodsType || 0),
        status: parseInt(options.status || 0),
        tag: decodeURIComponent(options.tag || ''),
        days: parseInt(options.days || 0),
        received: options.received === 'true'
      }
    }
  },
  methods: {
    // 使用优惠券
    useCoupon() {
      // 根据优惠券类型跳转到不同的商品列表
      if (this.coupon.goodsType === 2) {
        // 指定商品类型，跳转到指定商品列表
        uni.navigateTo({
          url: '/pages/goods-list/index?couponId=' + this.coupon.id
        })
      } else {
        // 全场通用类型，跳转到商品列表
        uni.switchTab({
          url: '/pages/category/index'
        })
      }
    },
    
    // 领取优惠券
    receiveCoupon() {
      if (this.coupon.received) return
      
      uni.showLoading({
        title: '领取中...'
      })
      
      this.$post('coupon/receive', {
        couponId: this.coupon.id
      })
        .then(res => {
          if (res.errno === 0) {
            uni.showToast({
              title: '领取成功',
              icon: 'success'
            })
            // 更新优惠券状态
            this.coupon.received = true
            
            // 延迟跳转到我的优惠券页面
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/coupon/user'
              })
            }, 1500)
          } else {
            uni.showToast({
              title: res.errmsg || '领取失败',
              icon: 'none'
            })
          }
        })
        .catch(error => {
          console.error('领取优惠券失败', error)
          uni.showToast({
            title: '领取失败',
            icon: 'none'
          })
        })
        .finally(() => {
          uni.hideLoading()
        })
    },
    
    // 格式化金额
    formatAmount(amount) {
      return parseFloat(amount).toFixed(2)
    },
    
    // 格式化日期（简短）
    formatDate(dateStr) {
      if (!dateStr) return ''
      // 处理iOS兼容性问题，将yyyy-MM-dd HH:mm:ss格式转换为yyyy/MM/dd HH:mm:ss
      dateStr = dateStr.replace(/-/g, '/')
      const date = new Date(dateStr)
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '日期无效'
      }
      return `${date.getMonth() + 1}.${date.getDate()}`
    },
    
    // 格式化日期（完整）
    formatFullDate(dateStr) {
      if (!dateStr) return ''
      // 处理iOS兼容性问题，将yyyy-MM-dd HH:mm:ss格式转换为yyyy/MM/dd HH:mm:ss
      dateStr = dateStr.replace(/-/g, '/')
      const date = new Date(dateStr)
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '日期无效'
      }
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/common/theme.scss';

.coupon-detail {
  min-height: 100vh;
  background-color: $bg-main;
  padding-bottom: 150rpx;
}

.coupon-card {
  margin: 20rpx 40rpx 40rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 2;
  
  &.used, &.expired {
    opacity: 0.8;
    
    .coupon-top {
      background-color: #999 !important;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotate(-30deg);
      width: 200rpx;
      height: 200rpx;
      background: rgba(0, 0, 0, 0.1);
      border-radius: 50%;
      z-index: 1;
    }
  }
  
  &.used::before, &.expired::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 160rpx;
    height: 160rpx;
    background: url('/static/images/common/used.png') no-repeat center;
    background-size: contain;
    z-index: 2;
  }
  
  &.expired::before {
    background-image: url('/static/images/common/expired.png');
  }
  
  .coupon-top {
    background-color: #b84a39; /* 默认颜色 */
    padding: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    
    &.discount-coupon {
      background-color: #FF9500;
    }
    
    &.free-coupon {
      background-color: #5E35B1;
    }
    
    &.gray-coupon {
      background-color: #999 !important;
    }
    
    &::after {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 20rpx;
      background: radial-gradient(circle at top, transparent 10rpx, #fff 10rpx);
      background-size: 20rpx 20rpx;
      background-position: 0 -10rpx;
    }
    
    .coupon-tag {
      position: absolute;
      top: 0rpx;
      left: 0rpx;
      font-size: 16rpx;
      color: #fff;
      padding: 2rpx 6rpx;
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 4rpx;
    }
    
    .coupon-amount {
      display: flex;
      align-items: baseline;
      margin-bottom: 20rpx;
      
      .amount {
        font-size: 80rpx;
        font-weight: bold;
        color: #fff;
        line-height: 1;
      }
      
      .unit {
        font-size: 36rpx;
        color: #fff;
        margin-left: 8rpx;
      }
    }
    
    .coupon-name {
      font-size: 36rpx;
      color: #fff;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .coupon-desc {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.8);
    }
  }
  
  .coupon-bottom {
    background-color: #fff;
    padding: 40rpx;
    
    .coupon-time, .coupon-condition, .coupon-scope {
      display: flex;
      margin-bottom: 20rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        font-size: 28rpx;
        color: #999;
        width: 160rpx;
      }
      
      .value {
        flex: 1;
        font-size: 28rpx;
        color: $primary-dark-pink;
      }
    }
  }
}

.rules-section {
  margin: 0 40rpx 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: $primary-dark-pink;
    margin-bottom: 30rpx;
    position: relative;
    padding-left: 20rpx;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 8rpx;
      height: 30rpx;
      background-color: $primary-pink;
      border-radius: 4rpx;
    }
  }
  
  .rules-content {
    .rule-item {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 16rpx;
      position: relative;
      padding-left: 20rpx;
      
      &::before {
        content: '•';
        position: absolute;
        left: 0;
        top: 0;
      }
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 30rpx 40rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
  
  .action-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background-color: $gradient-button;
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 45rpx;
    
    &.disabled {
      background-color: #ccc;
      color: #fff;
    }
    
    &.use-btn {
      background-color: $gradient-button;
    }
    
    &.receive-btn {
      background-color: $gradient-button;
      
      &.disabled {
        background-color: #ccc;
      }
    }
  }
}
</style> 